<?php
namespace app\admin\controller;

use app\AdminCollection;
use app\model\Admin;
use app\model\AdminGroup;
use app\model\AdminLoginLog;
use My\Tool;
use My\Validate;

class Manager extends AdminCollection
{

    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $page = input('page') ? input('page') : 1;
        $orderkey = pagesize * ($page - 1);
        $list = Admin::pageService();
        $_list = array();
        foreach ($list as $key => $val) {
            $_t = $val;
            $_t['orderkey'] = $orderkey += 1;
            $adminGroupFind = AdminGroup::findService(['admin_group_id' => $val['group_id']], ['name']);
            $_t['group_name'] = $adminGroupFind['name'];
            $_t['login_time'] = $val['login_time'] != 0 ? date('Y-m-d H:i:s', $val['login_time']) : '0000-00-00 00:00:00';
            $_t['statusString'] = $this->getConfig('admin_status', $val['status']);
            $_t['deleteUrl'] = url('manager/delete', array('admin_id' => $val['admin_id']));
            $_t['updateUrl'] = url('manager/update', array('admin_id' => $val['admin_id']));
            $_t['statusUrl'] = url('manager/status', array('admin_id' => $val['admin_id']));
            $_list[] = $_t;
        }
        $pages = $list->render();
        $this->assign('list', $_list);
        $this->assign('pages', $pages);
        return $this->fetch();
    }

    //添加管理员
    public function add()
    {
        $submit = input('submit');
        if ($submit) {
            try {
                $input = input('');
                $data = $input['info'];
                $username = $data['username'];
                $password = $data['password'];
                $confirmpassword = $data['confirmpassword'];
                $name = $data['name'];
                $group_id = $data['group_id'];
                if (Validate::checkNull($username)) throw new \Exception("请输入登录名称");
                if (Validate::checkMinLength($username, 4)) throw new \Exception("请输入最少4位的登录名称");
                if (Validate::checkNull($password)) throw new \Exception("请输入登录密码");
                if (Validate::checkMinLength($password)) throw new \Exception("请输入最少6位的密码");
                if (Validate::checkNull($confirmpassword)) throw new \Exception("请输入确认密码");
                if (Validate::checkNoEqual($password, $confirmpassword)) throw new \Exception("两次输入密码不一致");
                if (Validate::checkNull($name)) throw new \Exception("请输入用户名称");
                if (Validate::checkNull($group_id)) throw new \Exception("请选择管理员组");
                $adminFindService = Admin::findService(['username' => $username]);
                if ($adminFindService) throw new \Exception("登录名称已经存在，请重新输入登录名称");
                $salt = Tool::randomNumber();
                $data['password'] = Tool::encryptionFunction($password, $salt);
                $data['salt'] = $salt;
                unset($data['confirmpassword']);
                $return = Admin::addService($data);
                if ($return) {
                    $this->returnSuccess("提交数据成功");
                } else {
                    throw new \Exception("提交数据失败");
                }
            } catch (\Exception $e) {
                $this->returnError($e->getMessage());
            }
        } else {
            $groupList = AdminGroup::listService(['status' => 1]);
            $this->assign('groupList', $groupList);
            return $this->fetch();
        }
    }

    //删除管理员
    public function delete()
    {
        try {
            $admin_id = input('admin_id');
            if (Validate::checkNull($admin_id)) throw new \Exception('删除失败');
            if ($admin_id == config('default_admin_id')) throw new \Exception('系统默认管理员不能删除');
            $return = Admin::deleteService(['admin_id' => $admin_id]);
            if ($return) {
                $this->returnSuccess("删除数据成功");
            } else {
                throw new \Exception("删除数据失败");
            }
        } catch (\Exception $e) {
            $this->returnError($e->getMessage());
        }
    }

    //编辑资料
    public function update()
    {
        $submit = input('submit');
        if ($submit) {
            try {
                $input = input('');
                $where = $input['where'];
                $data = $input['info'];
                $password = $data['password'];
                $confirmpassword = $data['confirmpassword'];
                $name = $data['name'];
                if ($password) {
                    if (Validate::checkNull($password)) throw new \Exception("请输入登录密码");
                    if (Validate::checkMinLength($password)) throw new \Exception("请输入最少6位的密码");
                    if (Validate::checkNull($confirmpassword)) throw new \Exception("请输入确认密码");
                    if (Validate::checkNoEqual($password, $confirmpassword)) throw new \Exception("两次输入密码不一致");
                    $salt = Tool::randomNumber();
                    $data['password'] = Tool::encryptionFunction($password, $salt);
                    $data['salt'] = $salt;
                    unset($data['confirmpassword']);
                } else {
                    unset($data['password']);
                    unset($data['confirmpassword']);
                }
                if (Validate::checkNull($name)) throw new \Exception("请输入用户名称");
                if ($where['admin_id'] != config('default_admin_id')) {
                    $group_id = $data['group_id'];
                    if (Validate::checkNull($group_id)) throw new \Exception("请选择管理员组");
                }
                Admin::updateServer($where, $data);
                $this->returnSuccess("提交数据成功", $this->getPrevious());
            } catch (\Exception $e) {
                $this->returnError($e->getMessage());
            }
        } else {
            $admin_id = input('admin_id');
            if (Validate::checkNull($admin_id)) $this->returnError('系统发生致命错误');
            $where = ['admin_id' => $admin_id];
            $adminFindService = Admin::findService($where);
            if (Validate::checkEmpty($adminFindService)) $this->returnError('系统发生致命错误');
            if ($this->getAdmin() != config('default_admin_id')) {
                if ($admin_id == config('default_admin_id')) $this->returnError('权限不足，不能操作');
            }
            $this->assign('adminFindService', $adminFindService);
            $this->assign('admin_id', $admin_id);
            $this->assign('default_admin_id', config('default_admin_id'));
            $this->assign('REFERER', $this->previousUrl());
            $groupList = AdminGroup::listService(['status' => 1]);
            $this->assign('groupList', $groupList);
            return $this->fetch();
        }
    }

    //修改状态
    public function status()
    {
        $admin_id = input('admin_id');
        if (Validate::checkNull($admin_id)) $this->returnError('系统发生致命错误');
        $where = ['admin_id' => $admin_id];
        $adminFindService = Admin::findService($where);
        if (Validate::checkEmpty($adminFindService)) $this->returnError('系统发生致命错误');
        if ($this->getAdmin() != config('default_admin_id')) {
            if ($admin_id == config('default_admin_id')) $this->returnError('权限不足，不能操作');
        }
        switch ($adminFindService['status']) {
            case 0:
                $status = 1;
                break;
            case 1:
                $status = 0;
                break;
            case 2:
                $status = 1;
                break;
        }
        $data = ['status' => $status];
        $return = Admin::updateServer($where, $data);
        if ($return) {
            $this->returnSuccess("提交数据成功");
        } else {
            $this->returnError("提交数据失败");
        }
    }


    //修改登录账号密码
    public function passwordlogin()
    {
        $submit = input('submit');
        if ($submit) {
            $input = input('');
            $data = $input['info'];
            $originalpassword = $data['originalpassword'];
            $password = $data['password'];
            $confirmpassword = $data['confirmpassword'];
            if (Validate::checkNull($originalpassword)) $this->returnError("请输入原来密码");
            if (Validate::checkNull($password)) $this->returnError("请输入新的密码");
            if (Validate::checkMinLength($password)) $this->returnError("请输入最少6位的密码");
            if (Validate::checkNull($confirmpassword)) $this->returnError("请输入确认密码");
            if (Validate::checkNoEqual($password, $confirmpassword)) $this->returnError("两次输入密码不一致");
            $findService = Admin::findService(['admin_id' => $this->getAdmin()]);
            $original = Tool::encryptionFunction($originalpassword, $findService['salt']);
            if (Validate::checkNoEqual($findService['password'], $original)) $this->returnError("原来密码输入不正确");
            $salt = Tool::randomNumber();
            $data_update = array();
            $data_update['password'] = Tool::encryptionFunction($password, $salt);
            $data_update['salt'] = $salt;
            Admin::updateServer(['admin_id' => $this->getAdmin()], $data_update);
            $this->returnSuccess("提交数据成功");
        } else {
            $this->assign('username', $this->adminUsername());
            return $this->fetch();
        }
    }

    //修改登录账号资料
    public function updatelogin()
    {
        $submit = input('submit');
        if ($submit) {
            $input = input('');
            $data = $input['info'];
            if (Validate::checkNull($data['name'])) $this->returnError("请输入用户名称");
            Admin::updateServer(['admin_id' => $this->getAdmin()], $data);
            $this->returnSuccess("提交数据成功");
        } else {
            $findService = Admin::findService(['admin_id' => $this->getAdmin()]);
            $findService['login_time'] = date('Y-m-d H:i:s', $findService['login_time']);
            $this->assign('findService', $findService);
            return $this->fetch();
        }
    }

    /**
     * 登录日记
     * @return mixed
     */
    public function log()
    {
        $page = input('page') ? input('page') : 1;
        $orderkey = pagesize * ($page - 1);
        $list = AdminLoginLog::pageService();
        $_list = array();
        foreach ($list as $key => $val) {
            $_t = $val;
            $_t['orderkey'] = $orderkey += 1;
            $adminfind = Admin::findService(['admin_id' => $val['admin_id']], ['name']);
            $_t['name'] = $adminfind['name'];
            $_t['login_time'] = $val['login_time'] != 0 ? date('Y-m-d H:i:s', $val['login_time']) : '0000-00-00 00:00:00';
            $_list[] = $_t;
        }
        $pages = $list->render();
        $this->assign('list', $_list);
        $this->assign('pages', $pages);
        return $this->fetch();
    }

}
